package com.zbf.dbconfig;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/3/24  0:11
 * 描述:
 */
@Configuration
@MapperScan(basePackages = {"com.zbf.dao2"},sqlSessionFactoryRef = "sqlsessionFactory2")
public class Db2Config {

    @Autowired
    private Db2 db2;

    @Bean(name = "dataSource2")
    public DataSource getDataSource(){

        DataSource build = DataSourceBuilder.create()
                .driverClassName(db2.getDriverClassName())
                .password(db2.getPassword())
                .username(db2.getUserName())
                .url(db2.getUrl())
                .build();

        return build;
    }

    @Bean(name = "datasourceTransactionManager2")
    public DataSourceTransactionManager getDataSourceTransactionManager(@Qualifier("dataSource2") DataSource dataSource){
       return new DataSourceTransactionManager(dataSource);
    }


    @Bean("sqlsessionFactory2")
    public SqlSessionFactory getSqlSessionFactory(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().
                getResources("classpath*:/mapper/db2/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }


}
